package la.iok.hzsvn.lewin.movie.service;

import la.iok.hzsvn.lewin.movie.config.DfsProperties;
import la.iok.hzsvn.lewin.movie.core.exception.ErrorCode;
import la.iok.hzsvn.lewin.movie.entity.PlayRoleBook;
import la.iok.hzsvn.lewin.movie.entity.PlayRoleBookFile;
import la.iok.hzsvn.lewin.movie.entity.PlayRoleBookImage;
import la.iok.hzsvn.lewin.movie.entity.PlayRoleBookInstance;
import la.iok.hzsvn.lewin.movie.mapper.PlayRoleBookFileMapper;
import la.iok.hzsvn.share.annotations.NotNull;
import la.iok.hzsvn.share.annotations.Nullable;
import la.iok.hzsvn.share.dfs.model.DfsDescriptor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

@Service
public class PlayRoleBookFileServiceImpl extends MovieFileServiceImpl<PlayRoleBookFile, PlayRoleBookFileMapper> implements PlayRoleBookFileService {
    public PlayRoleBookFileServiceImpl(PlayRoleBookFileMapper mapper,
                                       WebDfsService webDfsService, DfsProperties dfsProperties) {
        super(mapper, webDfsService, dfsProperties);
    }

    @Override
    public void downloadFile(@NotNull HttpServletResponse response, @Nullable Long fileId, @NotNull String name) {
        PlayRoleBookFile file = select(fileId);
        ErrorCode.RECORD_NOT_EXIST.assertNotNull(file,name);
        DfsDescriptor descriptor = webDfsService.dfsFile(file.getPath());
        ErrorCode.PROPERTY_CHECK_ERROR.assertTrue(webDfsService.exist(descriptor),()->new Object[]{"电子书文件",name + "的文件不存在"});
        webDfsService.downloadFile(response,descriptor,file.getFileName());
    }

    @Override
    protected void validateReference(@NotNull PlayRoleBookFile file) {
        PlayRoleBookInstance item = executeSelect(PlayRoleBookInstance.class,"select * from "
                + PlayRoleBookInstance.class.getSimpleName() + " where fileDeleted=0 and (fileId=" + file.getId() + " or htmlId=" + file.getId() + ") limit 1");
        ErrorCode.FILE_REFERENCED_BY_OTHER.assertNull(item,file.getPath(),PlayRoleBookInstance.class.getSimpleName());

        PlayRoleBook item2 = executeSelect(PlayRoleBook.class,"select * from "
                + PlayRoleBook.class.getSimpleName() + " where fileId=" + file.getId() + " limit 1");
        ErrorCode.FILE_REFERENCED_BY_OTHER.assertNull(item2,file.getPath(),PlayRoleBook.class.getSimpleName());

        PlayRoleBookImage item3 = executeSelect(PlayRoleBookImage.class,"select * from "
                + PlayRoleBookImage.class.getSimpleName() + " where fileDeleted=0 and fileId=" + file.getId() + " limit 1");
        ErrorCode.FILE_REFERENCED_BY_OTHER.assertNull(item3,file.getPath(),PlayRoleBookImage.class.getSimpleName());
    }
}
